package org.example;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache {

    // 容量
    private final int capacity;

    private final LinkedHashMap<Integer,Integer> cache = new LinkedHashMap<Integer, Integer>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            return size() > LRUCache.this.capacity;
        }
    };

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public void put(int key, int value) {
        cache.remove(key);
        cache.put(key, value);
    }

    public int get(int key) {
        if (!cache.containsKey(key)) {
            return -1;
        } else {
            int val = cache.get(key);
            cache.remove(key);
            cache.put(key,val);
            return val;
        }

    }
}
